<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--表格部分-->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCategoryDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table
        :data="catelist"
        :columns="cateColumns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="序号"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCategoryById(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 9, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!--添加分类对话框-->
    <el-dialog title="添加分类" width="50%" :visible.sync="addDialogVisable" @close="addDialogClose">
      <!--添加分类表单-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            v-model="selectKeys"
            :options="parentCategories"
            :props="cascaderProps"
            @change="parentCategoryChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改分类对话框-->
    <el-dialog title="修改分类" width="50%" :visible.sync="editDialogVisable" @close="editDialogClose">
      <!--修改分类表单-->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="editCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagesize: 5,
        pagenum: 1
      },
      catelist: [],
      cateColumns: [
        { label: '分类名称', prop: 'cat_name', width: '100px' },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          width: '50px',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          width: '50px',
          type: 'template',
          template: 'level'
        },
        { label: '操作', width: '200px', type: 'template', template: 'opt' }
      ],
      total: 0,
      addDialogVisable: false,
      addForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 表单的验证规则对象
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 下拉框父分类数据
      parentCategories: [],
      // 指定
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 选中的父级分类
      selectKeys: [],
      editDialogVisable: false,
      editForm: {},
      // 表单的验证规则对象
      eidtFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.catelist = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCategoryList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCategoryList()
    },
    addCategoryDialog() {
      this.getParentCategories()
      this.addDialogVisable = true
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
      this.selectKeys = []
    },
    // 添加分类
    addCategory() {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res && res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        // 关闭对话框
        this.addDialogVisable = false
        // 刷新列表
        this.getCategoryList()
        this.$message.success('success')
      })
    },
    async getParentCategories() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.parentCategories = res.data
    },
    // 选择项发生变化触发
    parentCategoryChange() {
      const length = this.selectKeys.length
      this.addForm.cat_level = length
      if (length > 0) {
        this.addForm.cat_pid = this.selectKeys[length - 1]
      } else {
        this.addForm.cat_pid = 0
      }
    },
    // 修改分类
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editDialogVisable = true
    },
    editDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    editCategory() {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.put(
          'categories/' + this.editForm.cat_id,
          {
            cat_name: this.editForm.cat_name
          }
        )
        if (res && res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 关闭对话框
        this.editDialogVisable = false
        // 刷新列表
        this.getCategoryList()
        this.$message.success(res.meta.msg)
      })
    },
    // 删除分类
    async removeCategoryById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了该操作')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 刷新列表
      this.getCategoryList()
      this.$message.success(res.meta.msg)
    }
  }
}
</script>
<style lang="less" scoped>
.zk-table {
    margin-top: 15px;
    font-size: 13px;
}

.el-cascader {
    width: 100%;
}
</style>
